import { Component, Injectable, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { Lodop, LodopService } from '@shared/apes/lodop';
import { dateFormat, getJson } from '../../../utils/utils';
import { Observable } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { toNumber } from '@shared/apes/core';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { ApesModalRef, ApesModalService } from '@shared/apes/modal';


@Injectable({
  providedIn: 'root',
})

export class BatchPrintService {

  error = false;
  lodop: Lodop = null;
  isPreview: boolean = true;

  constructor(
    private msg: ApesMessageService,
    private apiService: ApiService,
    public lodopSrv: LodopService,
    protected expressionService: ExpressionService,
    private modalService: ApesModalService,
  ) {
    this.lodopSrv.lodop.subscribe(({ lodop, ok }) => {
      if (!ok) {
        this.error = true;
        return;
      }
      this.error = false;
      this.lodop = lodop;
    });
  }

  public batchPrint(type, initData) {
    let setData = [];
    initData.forEach((data) => {
      setData.push(data['id'] ? data['id'] : data['ID']);
    });
    if (!this.lodop) {
      this.msg.error('请安装lodop打印工具');
      return;
    }

    if (setData.length == 0) {
      this.msg.error('请勾选需要打印数据');
      return;
    }
    switch (type) {
      case 'repairOrder':
        this.repairOrderTemplate(setData);
        break;
      case 'glVoucher':
        this.glVoucherTemplate(setData);
        break;
      default :
        this.msg.error('未设置对应打印模版');
        break;
    }
  }

  private repairOrderTemplate(setData) {
    this.apiService.post('purchase.after.junior.findByIds', setData).subscribe((body) => {
      console.log(body);
      let LODOP = this.lodop;
      LODOP.SET_PRINT_PAGESIZE(2, 0, 0, 'A5');
      LODOP.PRINT_INIT(null);
      /*抬头*/
      let addHeadHTM = function(jsonData) {
        let id = jsonData['id'];
        let locationName = jsonData['location'].name;
        let supplierName = jsonData['supplier'].name;
        let applyDate = jsonData['applyDate'];
        let applyUid = jsonData['applyUid'].name;
        let nowDate = dateFormat('yyyy-MM-dd HH:mm:ss', new Date());
        let textHtml =
          `<div id="div1">
            <div style="line-height: 35px">
              <strong><h2 align="center">售后鉴定单</strong></h2>
            </div>
            <table border=0 cellSpacing=0 cellPadding=0 style="width: 100%;font-size: 15px; line-height: 20px;">
              <tbody>
                <tr>
                  <td style="width: 150px;">售后单号：
                    <span>${id}</span>
                  </td>
                  <td style="width: 150px;">&nbsp;&nbsp;&nbsp;&nbsp;业务员：${applyUid}</td>
                  <td style="width:60px;">供应商：</td>
                  <td>
                    ${supplierName}
                  </td>
                </tr>
                <tr>
                  <td style="width: 280px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;仓库：${locationName}</td>
                  <td style="width: 250px;">制单日期：<span>${applyDate}</span></td>
                </tr>
                <tr>
                  <td>打印时间：<span>${nowDate}</span></td>
                </tr>
              </tbody>
            </table>
          </div>`;
        return textHtml;
      };
      /*表格数据*/
      let addHTM = function(jsonData) {
        let textHtml = '<TABLE border=1 cellSpacing=0 cellPadding=1 style="font-size: 15px;border-collapse:collapse" bordercolor="#333333" line-height: 20px;>'
          + '       <tr bgcolor="#FFFFFF" align="center">'
          + '               <td  align="center" >序号</td>'
          + '               <td  align="center" >商品编码</td>'
          + '               <td  align="center" >商品名称</td>'
          + '               <td  align="center" >单位</td>'
          + '               <td  align="center" >数量</td>'
          + '               <td  align="center" >单价</td>'
          + '               <td  align="center" >金额</td>'
          + '               <td  align="center" >鉴定结果</td>'
          + '               <td  align="center" >备注</td>'
          + '       </tr>';
        let textHtml2 = '';
        let iMX_LEN = jsonData.length;
        let qty = 0;
        let sum = 0;
        for (let j = 0; j < iMX_LEN; j++) {
          let XH = j + 1;
          let productId = jsonData[j]['product'].id;
          let productName = jsonData[j]['product'].name;
          let uom = jsonData[j]['uom'].name;
          let productQty = jsonData[j]['productQty'];
          let priceUnit = jsonData[j]['priceUnit'];
          let total = jsonData[j]['priceUnit'] * jsonData[j]['productQty'];
          let note = jsonData[j]['note'];
          if (note == undefined) note = '';
          qty += jsonData[j]['productQty'];
          sum += total;
          textHtml2 += '<tr bgcolor="#FFFFFF">'
            + '<td align="center" width="60px">' + XH + '</td>'
            + '<td align="center" width="120px">' + productId + '</td>'
            + '<td align="center" width="270px">' + productName + '</td>'
            + '<td align="center" width="50px">' + uom + '</td>'
            + '<td align="center" width="50px">' + productQty + '</td>'
            + '<td align="center" width="50px">' + priceUnit + '</td>'
            + '<td align="center" width="50px">' + total + '</td>'
            + '<td width="70px">&nbsp;&nbsp;&nbsp;&nbsp;</td>'
            + '<td align="center" width="50px">' + note + '</td>'
            + '</tr>';
        }
        let strHTML = '';
        let string1 = textHtml + textHtml2;
        strHTML = strHTML + string1 + ''
          + '<tfoot>'
          + '<tr>'
          + '<TD tdata="pageNO" format="#" align="center">'
          + '<p align="center"><span tdata="pageNO">##</span> /<span tdata="pageCount">##</span></TD>'
          + '<TD colspan="8" align="center"><span style="margin-left: 250px">数量总计：' + qty + '</span><span style="margin-left: 70px">金额总计：' + sum.toFixed(2) + '</span></TD>'

          // + '<TD tdata="subSum" format="#,##0.00" align="right">###元</TD>'
          // + '<TD tdata="subSum" format="#,##0.00" align="right">###元</TD>'
          // + '</TD>'
          //                +'<TD tdata="pageCount" format="#" align="left"><p align="left"><b>总##页</b></TD>'
          + '</tr>'
          + '</tfoot></table>';
        return strHTML;
      };

      /*页脚*/
      let addFooterHTM = function(jsonData) {
        let textHtml = '<div id="div2">'
          + '<TABLE border=0 cellSpacing=0 cellPadding=0 width="100%" style="margin-top: 12px;line-height: 20px;">'
          + '<TBODY>'
          + '<TR>'
          + '<TD align="left" width="150px">仓库人签名：<SPAN></SPAN></TD>'
          + '<TD align="left" width="120px">发货人：<SPAN></SPAN></TD>'
          + '<TD align="left" width="120px">鉴定人：<SPAN></SPAN></TD>'
          + '<TD align="left" width="140px">厂家取单人：<SPAN></SPAN></TD>'
          + '</TR>';
        '</TBODY>' +
        '</TABLE>'
        + '</div>';
        return textHtml;
      };

      /*获取要打印的数据*/
      let jsonCWPZ = body;
      let iSIZE = jsonCWPZ.length;
      let iLinkedItem = 0;
      for (let i = 0; i < iSIZE; i++) {
        if (i > 0) {
          LODOP.NewPageA();
        }
        let jsonCWPZData = jsonCWPZ[i];
        LODOP.ADD_PRINT_TABLE(190, '3%', '94%', 328, addHTM(jsonCWPZData['purchaseAfterJuniorItems']));
        LODOP.SET_PRINT_STYLEA(0, 'Vorient', 3);
        LODOP.ADD_PRINT_HTM(26, '3%', '94%', 160, addHeadHTM(jsonCWPZData));
        LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
        LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', iLinkedItem * 3 + 1);
        LODOP.ADD_PRINT_HTM(518, '5%', '90%', 20, addFooterHTM(jsonCWPZData));
        LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', iLinkedItem * 3 + 1);
//            LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
//            LODOP.SET_PRINT_STYLEA(0,"LinkedItem",iLinkedItem*3+1);
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', 12);
        LODOP.SET_PRINT_STYLEA(0, 'FontColor', '#FF0000');
        LODOP.SET_PRINT_STYLEA(0, 'Alignment', 2);
        LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
        LODOP.SET_PRINT_STYLEA(0, 'Horient', 3);
        iLinkedItem = iLinkedItem + 1;
      }


      LODOP.ADD_PRINT_HTM(1, 600, 300, 100, '');
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);

      LODOP.SET_PRINT_STYLEA(0, 'Horient', 1);
      //LODOP.ADD_PRINT_TEXT(3,34,196,20,"总页眉：凭证");
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
      LODOP.PREVIEW();
    });
  }

  private glVoucherTemplate(setData) {
    this.apiService.post('fin.glVoucher.findByIds', setData).subscribe((body) => {
      console.log(body);
      let LODOP = this.lodop;
      LODOP.SET_PRINT_PAGESIZE(2, 0, 0, 'A4');
      LODOP.PRINT_INIT(null);
      /*抬头*/
      let addHeadHTM = function(jsonData) {
        let id = jsonData['id'];
        let companyName = jsonData['company'].name;
        let postDate = jsonData['postDate'];
        let createDate = jsonData['createDate'];
        let voucherNo = jsonData['voucherNo'];
        let attachment = jsonData['attachment'];
        let remark = jsonData['remark'];
        if (remark == undefined) remark = '';
        let period = jsonData['period'];
        let voucherTypeName = jsonData['accountingVoucherType'].name;
        let nowDate = dateFormat('yyyy-MM-dd HH:mm:ss', new Date());
        let textHtml =
          `<div id="div1">
            <div style="line-height: 1">
              <strong><h2 align="center">${companyName}</strong></h2>
              <strong><h3 align="center">记账凭证</strong></h3>
            </div>

            <table border=0 cellSpacing=0 cellPadding=0 style="width: 100%;font-size: 15px; line-height: 20px; margin-bottom: 20px">
              <tbody>
                <tr>
                  <td style="width: 150px;">凭证内码：
                    <span>${id}</span>
                  </td>
                  <td style="width: 200px;"></td>
                  <td style="width: 200px;">业务日期：<span>${postDate}</span></td>
                </tr>
                <tr>
                  <td style="width: 150px;">会计年度：<span>${period}</span></td>
                  <td style="width: 200px;"></td>
                  <td style="width: 200px;">制单日期：<span>${createDate}</span></td>
                </tr>
                <tr>
                  <td style="width: 300px;">凭证类别：<span>${voucherTypeName}</span></td>
                  <td style="width: 50px;">附件数：<span>${attachment}</span></td>
                  <td style="width: 200px;">凭证号：<span>${voucherNo}</span></td>
                </tr>
                <tr>
                  <td style="width: 550px;" colspan="3">备注：<span>${remark}</span></td>
                </tr>
                <tr>
                  <td style="width: 300px;" colspan="3">打印时间：<span>${nowDate}</span></td>
                </tr>
              </tbody>
            </table>
          </div>`;
        return textHtml;
      };
      /*表格数据*/
      let addHTM = function(jsonData) {
        let textHtml = '<TABLE border=1 cellSpacing=0 cellPadding=1 style="font-size: 14px;border-collapse:collapse;margin-bottom: 20px" bordercolor="#333333" line-height: 30px;>'
          + '       <tr bgcolor="#FFFFFF" align="center">'
          + '               <td  align="center" >序号</td>'
          + '               <td  align="center" >摘要</td>'
          + '               <td  align="center" >科目</td>'
          + '               <td  align="center" >借方</td>'
          + '               <td  align="center" >贷方</td>'
          + '       </tr>';
        let textHtml2 = '';
        let qty = 0;
        let sum = 0;
        let debitTotal = 0;
        let creditTotal = 0;
        // tslint:disable-next-line:prefer-for-of
        for (let j = 0; j < jsonData.length; j++) {
          let orderNum = jsonData[j]['orderNum'];
          orderNum = orderNum + 1;
          let summary = jsonData[j]['summary'];
          if (summary == undefined) summary = '';
          let chartName = jsonData[j]['accountingOperatingChart'].name;
          let debit = jsonData[j]['debit'];
          let credit = jsonData[j]['credit'];
          let creditF = toThousands(credit);
          let debitF = toThousands(debit);
          debitTotal += debit;
          creditTotal += credit;
          sum += 0;
          textHtml2 += '<tr bgcolor="#FFFFFF" style="height:30px;">'
            + '<td align="center" width="40px">' + orderNum + '</td>'
            + '<td align="left" width="360px">' + summary + '</td>'
            + '<td align="left" width="280px">' + chartName + '</td>'
            + '<td align="right" width="120px" style="padding-right: 5px">' + debitF + '</td>'
            + '<td align="right" width="120px" style="padding-right: 5px">' + creditF + '</td>'
            + '</tr>';
        }
        let strHTML = '';
        let totalChina = numberParseChina(debitTotal);
        let creditTotalF = toThousands(creditTotal.toFixed(2));
        let debitTotalF = toThousands(debitTotal.toFixed(2));
        let string1 = textHtml + textHtml2;
        strHTML = strHTML + string1 + ''
          + '<tfoot>'
          + '<tr style="height:30px;">'
          + '<TD tdata="pageNO" format="#" align="center">'
          + '<p align="center"><span tdata="pageNO">##</span> /<span tdata="pageCount">##</span></TD>'
          + '<TD align="left" colspan="2"><span>' + '大写：' + totalChina + '</span><span style="float:right">合计：</span></TD>'
          + '<TD align="right" colspan="1" style="padding-right: 5px"><span>' + debitTotalF + '</span></TD>'
          + '<TD align="right" colspan="1" style="padding-right: 5px"><span>' + creditTotalF + '</span></TD>'
          + '</tr>'
          + '</tfoot></table>';
        return strHTML;
      };

      /*页脚*/
      let addFooterHTM = function(jsonData) {
        debugger;
        let creatorName = jsonData['creatorName'] == null ? '' : jsonData['creatorName'].name;
        let approveName = jsonData['approveUID'] == undefined ? '' : jsonData['approveUID'].name;

        let textHtml =
          `<div id="div2" style="margin-top:20px">

            <div style="display: flex;justify-content:space-between;font-size:14px;">
              <div style="width:200px;padding: 0 5px; white-space:normal;word-break:break-all;word-wrap:break-word;"><b>制单人：</b><span>${creatorName}</span></div>
              <div style="width:200px;padding: 0 5px; white-space:normal;word-break:break-all;word-wrap:break-word;"><b>审核人：</b> <span>${approveName}</span></div>
              <div style="width:150px;padding: 0 5px;"><b>经办人：</b></div>
              <div style="width:150px;padding: 0 5px;"><b>过账人：</b></div>
              <div style="width:150px;padding: 0 5px;"><b>出纳：</b></div>
            </div>

          </div>`;
        return textHtml;
      };

      /*获取要打印的数据*/
      let jsonCWPZ = body;
      debugger;
      let iSIZE = jsonCWPZ.length;
      let iLinkedItem = 0;
      for (let i = 0; i < iSIZE; i++) {
        if (i > 0) {
          LODOP.NewPageA();
        }
        let jsonCWPZData = jsonCWPZ[i];
        LODOP.ADD_PRINT_TABLE(220, '3%', '94%', 328, addHTM(jsonCWPZData['voucherItemList']));
        LODOP.SET_PRINT_STYLEA(0, 'Vorient', 3);
        LODOP.ADD_PRINT_HTM(26, '3%', '94%', 220, addHeadHTM(jsonCWPZData));
        LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
        LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', iLinkedItem * 3 + 1);
        LODOP.ADD_PRINT_HTM(570, '3%', '95%', 60, addFooterHTM(jsonCWPZData));
        LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', iLinkedItem * 3 + 1);
//            LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
//            LODOP.SET_PRINT_STYLEA(0,"LinkedItem",iLinkedItem*3+1);
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', 12);
        LODOP.SET_PRINT_STYLEA(0, 'FontColor', '#FF0000');
        LODOP.SET_PRINT_STYLEA(0, 'Alignment', 2);
        LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
        LODOP.SET_PRINT_STYLEA(0, 'Horient', 3);
        iLinkedItem = iLinkedItem + 1;
      }


      LODOP.ADD_PRINT_HTM(1, 600, 300, 100, '');
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);

      LODOP.SET_PRINT_STYLEA(0, 'Horient', 1);
      //LODOP.ADD_PRINT_TEXT(3,34,196,20,"总页眉：凭证");
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1);
      LODOP.PREVIEW();
    });
  }

  public batchPrinting(formId, api, initData) {
    this.getPrintTemplate(formId, api, initData);
  }

  private getPrintTemplateApi(formId: string): Observable<any> {
    return this.apiService.post('form.get', { 'body': getJson({ id: formId }) }).pipe(map(
      (body) => {
        if (body) {
          return body;
        }
      }));
  }

  private getPrintTemplate(formId, api, initData) {
    this.getPrintTemplateApi(formId).pipe(
      map((body) => {
        return body;
      }),
    ).subscribe((body) => {
      let formMetadata = body;
      let setData = [];
      initData.forEach((data) => {
        setData.push(data['id'] ? data['id'] : data['ID']);
      });
      if (!this.lodop) {
        this.msg.error('请安装lodop打印工具');
        return;
      }

      if (setData.length == 0) {
        this.msg.error('请勾选需要打印数据');
        return;
      }

      if (setData.length == 1) {
        this.isPreview = true;
        this.getTemplateData(formMetadata, api, setData[0]);
      } else {
        this.isPreview = false;
        this.getPrintCopies((res) => {
          if (res != '' && res != null) {
            formMetadata.copies = res;
            setData.forEach((d) => {
              this.getTemplateData(formMetadata, api, d);
            });
          } else {
            setData.forEach((d) => {
              this.getTemplateData(formMetadata, api, d);
            });
          }
        });
      }
    });
  }

  private getPrintCopies(callback) {
    const openDialog = PrintCopiesComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '15vw',
      apesTitle: '批量打印份数',
      apesContent: openDialog,
      apesClosable: false,
      apesMaskClosable: false,
      apesFooter: [
        // {
        //   label: '取消',
        //   type: 'default',
        //   onClick: () => {
        //     dialogRef.close();
        //   },
        // },
        {
          label: '确定',
          type: 'primary',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['quantity']);
          },
        },
      ],
    });
    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  private getTemplateData(formMetadata, api, id) {
    this.apiService.post(api, { 'id': id }).subscribe(body => {
      console.log(body);
      let setData = body;
      this.recordPrint(setData);
      this.getConvertTemplate(formMetadata, setData);
    });
  }

  private recordPrint(setData) {
    this.apiService.post('print.record.setPrintRecordNumber', setData).subscribe((body) => {
      // console.log('打印记录', body);
    });
  }

  private getConvertTemplate(params, printData) {
    // let taskName = params.title;
    let sheet = params.sheet;
    let copies = params.copies ? params.copies : false;
    let table = {};
    let header = {};
    let footer = {};
    let custom = {};
    if (sheet.length != 0) {
      sheet.forEach((st) => {
        if (st && st.renderData) {
          st.renderData.forEach((params) => {
            switch (params.type) {
              case 'header' :
                header = {
                  html: this.convertHtmlTemplate(params, printData),
                  options: params,
                };
                break;
              case 'table':
                table = {
                  html: this.convertTableTemplate(params, printData),
                  options: params,
                };
                break;
              case 'footer':
                footer = {
                  html: this.convertHtmlTemplate(params, printData),
                  options: params,
                };
                break;
              case 'custom':
                custom = {
                  list: this.convertCustomStructure(params),
                  printData: printData,
                };
                break;
            }
          });
        }
      });
    }
    this.addPrintTemplate(header, footer, table, custom, copies);
  }

  private convertHtmlTemplate(params, printData) {
    let trList = this.convertHtmlStructure(params);
    let textHtml = this.spliceMainHTML(trList, printData);
    console.log(textHtml);
    return textHtml;
  }

  private convertTableTemplate(params, printData) {
    console.log('table', params);
    let trList = this.convertTableStructure(params);
    let id = params.title;
    let data = printData ? printData[id] : null;
    let textHtml = this.spliceTableHTML(trList, data);
    console.log(textHtml);
    return textHtml;
  }

  private convertCustomStructure(params) {
    let fields = params.fields;
    let list = [];
    fields.forEach((data) => {
      let options = {
        key: data.key,
        label: data.label,
        widget: data.type,
        ...data.templateOptions,
      };
      list.push(options);
    });
    console.log(list);
    return list;
  }

  private convertHtmlStructure(params) {
    let trList = [];
    params.fields.forEach((field) => {
      let options = {
        key: field.key,
        label: field.templateOptions.label,
        width: this.colToWidth(field.templateOptions.divCol),
        valueFormatter: field.templateOptions.valueFormatter,
        colspan: field.templateOptions.colspan,
      };

      let tr = field.templateOptions.tr;
      let existingTr = trList.find((item) => item.tr === tr); // 查找是否已经存在对应的表格行

      if (existingTr) {
        existingTr.list.push(options); // 如果已存在对应表格行，则将选项添加到其 list 中
      } else {
        trList.push({ tr: tr, list: [options] }); // 如果不存在对应表格行，则添加新的表格行对象到 list 数组中
      }
    });
    console.log('转换数据--', trList);
    return trList;
  }

  private convertTableStructure(params) {
    let trList = [];
    params.fields.forEach((field) => {
      let options = {
        key: field.key,
        label: field.templateOptions.label,
        width: this.colToWidth(field.templateOptions.divCol),
        valueFormatter: field.templateOptions.valueFormatter,
        textAlign: field.templateOptions.textAlign,
      };
      if (field.templateOptions.hasOwnProperty('sum')) {
        options['sum'] = true;
      }
      trList.push(options);
    });
    console.log('转换数据--', trList);
    return trList;
  }

  private spliceMainHTML(trList, printData) {
    let textHtml = `<table border=0 cellSpacing=0 cellPadding=0 style="width: 100%;font-size: 15px; line-height: 20px;">\r\n<tbody>\r\n`;
    trList.forEach((tr) => {
      textHtml += `<tr>\r\n`;
      tr.list.forEach((td) => {
        let data = '';
        if (printData && printData[td.key]) {
          data = this.valueFormatter(td, printData);
        }
        let width = td.width;
        let colspan = td.colspan ? td.colspan : null;
        textHtml +=
          `<td style="width: ${width}" colspan="${colspan}">${td.label} ${td.label ? ':' : ''}<span>${data}</span></td>\r\n`;
      });
      textHtml += `</tr>\r\n`;
    });
    textHtml += `</tbody>\r\n</table>`;
    return textHtml;
  }

  private spliceTableHTML(trList, printData) {
    let textHtml = `<table border=1 cellSpacing=0 cellPadding=1 style="width: 100%;font-size: 14px;border-collapse:collapse;margin-bottom: 20px; line-height: 20px;" bordercolor="#333333">\r\n<thead>\r\n`;
    textHtml += `<tr>\r\n`;
    let sumList = [];
    trList.forEach((td) => {
      let width = td.width;
      textHtml += `<td style="width: ${width};text-align:center;">${td.label}</td>\r\n`;
      if (td.hasOwnProperty('sum')) {
        sumList.push({ key: td.key, sum: 0 });
      }
    });
    textHtml += `</tr>\r\n</thead>\r\n`;
    if (printData && printData.length != 0) {
      textHtml += `<tbody>\r\n`;
      printData.forEach((item) => {
        textHtml += `<tr>\r\n`;
        trList.forEach((td) => {
          let data = '';
          if (item && item[td.key]) {
            data = this.valueFormatter(td, item);
          }
          let width = td.width;
          let textAlign = td['textAlign'] ? td['textAlign'] : 'left';
          textHtml +=
            `<td style="width: ${width};text-align: ${textAlign}">${data}</td>\r\n`;
          sumList.forEach((list) => {
            if (list.key == td.key) {
              list.sum += data;
            }
          });
        });
        textHtml += `</tr>\r\n`;
      });
      textHtml += `</tbody>\r\n`;
    }

    console.log(sumList);

    if (sumList.length != 0) {
      textHtml += `<tfoot>\r\n`;
      trList.forEach((td) => {
        let width = td.width;
        let textAlign = td['textAlign'] ? td['textAlign'] : 'left';
        let data = '';
        sumList.forEach((list) => {
          if (list.key == td.key) {
            data = (list.sum).toFixed(2);
          }
        });
        textHtml +=
          `<td style="width: ${width};text-align: ${textAlign}">${data}</td>\r\n`;
      });
      textHtml += `</tfoot>\r\n`;
    }

    textHtml += `</table>`;
    return textHtml;
  }

  private addPrintTemplate(header, footer, table, custom, copies) {
    let LODOP = this.lodop;
    // if (LODOP.CVERSION) {
    //   LODOP.On_Return = (taskID, value) => {
    //     this.value = value;
    //   };
    // }
    LODOP.PRINT_INIT('');
    // LODOP.SET_PRINT_PAGESIZE(2, '2160', '930', '');
    LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4');
    // LODOP.SET_PRINT_PAGESIZE(2, 0, 0, 'A5');

    if (copies) {
      LODOP.SET_PRINT_COPIES(copies);
    }

    this.addHTM(LODOP, header);

    this.addTable(LODOP, table);

    this.addHTM(LODOP, footer);

    if (Object.keys(custom).length !== 0) {
      this.addCustom(LODOP, custom);
    }

    if (this.isPreview) {
      // LODOP.PRINT_DESIGN();
      LODOP.PREVIEW();
    } else {
      LODOP.PRINT();
    }

  }

  private addHTM(LODOP, param) {
    let html = param.html;
    let options = param.options;

    LODOP.ADD_PRINT_HTM(options.top, options.left, options.width, options.height, html);
    LODOP.SET_PRINT_STYLEA(0, 'HOrient', 2);

    this.addStyle(LODOP, options);
  }

  private addTable(LODOP, param) {
    let html = param.html;
    let options = param.options;
    LODOP.ADD_PRINT_TABLE(options.top, options.left, options.width, options.height, html);

    // 水平位置锁定方式：0 左边 1 右边 2 居中 3 中间拉伸
    LODOP.SET_PRINT_STYLEA(0, 'HOrient', 2);

    // 垂直位置 锁定方式：0 上边 1 下边 2 居中 3 中间拉伸
    LODOP.SET_PRINT_STYLEA(0, 'Vorient', 3);

    // this.addStyle(LODOP, options);
  }

  private addCustom(LODOP, param) {
    console.log(param);
    let list = param.list;
    let printData = param.printData;
    list.forEach((li) => {
      this.addCustomTemplate(LODOP, li, printData);
    });
  }

  private addCustomTemplate(LODOP, param, printData) {
    let widget = param.widget;
    switch (widget) {
      case 'barcode':
        this.addBarcode(LODOP, param, printData);
        break;
      case 'text':
        this.addText(LODOP, param, printData);
        break;
    }
  }

  // 条形码
  private addBarcode(LODOP, param, printData) {
    let key = param.key;
    let value = printData[key];
    let type = param.type; // 条形码类型

    LODOP.ADD_PRINT_BARCODE(param.top, param.left, param.width, param.height, type, value);

    this.addStyle(LODOP, param);
  }

  // 纯文本
  private addText(LODOP, param, printData) {
    let value = this.valueFormatter(param, printData);

    LODOP.ADD_PRINT_TEXT(param.top, param.left, param.width, param.height, value);

    this.addStyle(LODOP, param);
  }

  // 打印样式
  private addStyle(LODOP, param) {

    // 字体：单位 px
    if (param.hasOwnProperty('fontSize')) {
      let fontSize = param.fontSize;
      LODOP.SET_PRINT_STYLEA(0, 'FontSize', fontSize);
    }

    // 字体颜色
    if (param.hasOwnProperty('fontColor')) {
      let fontColor = param.fontColor;
      LODOP.SET_PRINT_STYLEA(0, 'FontColor', fontColor);
    }

    // 字体粗体： 1 粗体 0 非粗
    if (param.hasOwnProperty('bold')) {
      let bold = param.bold;
      LODOP.SET_PRINT_STYLEA(0, 'Bold', bold);
    }

    // 基础属性：0 默认值 1 页眉页脚 2 页号 3 页数 4 多页项
    if (param.hasOwnProperty('itemType')) {
      let itemType = toNumber(param.itemType);
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', itemType);
    }

    // 设置关联项：整数 按顺序关联1开始 负数 按前一个对象关联 -1
    if (param.hasOwnProperty('linkedItem')) {
      let linkedItem = toNumber(param.linkedItem);
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', linkedItem);
    }
  }

  private valueFormatter(param, printData) {
    let key = param.key;
    let value = printData ? printData[key] : '';
    if (param.hasOwnProperty('valueFormatter') && param.valueFormatter) {
      value = this.formatter(value, param.valueFormatter);
    }
    if (value == null) {
      value = '';
    }
    return value;
  }

  private formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: value,
    });
  }

  private colToWidth(col) {
    let width;
    width = ((100 / 24) * col).toFixed(2) + '%';
    return width;
  }

}

@Component({
  selector: 'print-copies',
  template: `
    <div apes-row>
      <div apes-col>
        <span>每份单据打印份数：</span>
        <apes-input-number [apesMax]="10"
                           [apesMin]="1"
                           [apesPrecision]="0"
                           [(ngModel)]="quantity">

        </apes-input-number>
      </div>
    </div>
  `,
})
export class PrintCopiesComponent implements OnInit, OnDestroy {

  quantity: any = 1;

  constructor(
    private modal: ApesModalRef,
  ) {
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    this.modal.destroy(this.quantity);
  }
}

//数字格式化千分位
function toThousands(num) {
  if (isNaN(num)) {
    throw new TypeError('num is not a number');
  }

  let groups = (/([\-\+]?)(\d*)(\.\d+)?/g).exec('' + num);
  let mask = groups[1];            //符号位
  let integers = (groups[2] || '').split(''); //整数部分
  let decimal = groups[3] || '';       //小数部分
  let remain = integers.length % 3;

  let temp = integers.reduce(function(previousValue, currentValue, index) {
    if (index + 1 === remain || (index + 1 - remain) % 3 === 0) {
      return previousValue + currentValue + ',';
    } else {
      return previousValue + currentValue;
    }
  }, '').replace(/\,$/g, '');
  return mask + temp + decimal;
}


//阿拉伯数字转换成大写汉字
function numberParseChina(money) {
//汉字的数字
  let cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
  //基本单位
  let cnIntRadice = new Array('', '拾', '佰', '仟');
  //对应整数部分扩展单位
  let cnIntUnits = new Array('', '万', '亿', '兆');
  //对应小数部分单位
  let cnDecUnits = new Array('角', '分', '毫', '厘');
  //整数金额时后面跟的字符
  let cnInteger = '整';
  //整型完以后的单位
  let cnIntLast = '圆';
  //最大处理的数字
  let maxNum = 999999999999999.9999;
  //金额整数部分
  let integerNum;
  //金额小数部分
  let decimalNum;
  //输出的中文金额字符串
  let chineseStr = '';
  //分离金额后用的数组，预定义
  let parts;
  if (money == '') {
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //处理金额为负数问题
  let head = money < 0 ? '负' : '';
  money = Math.abs(money);

  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    let IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      let n = integerNum.substr(i, 1);
      let p = IntLen - i - 1;
      let q = p / 4;
      let m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    let decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      let n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return head + chineseStr;
}
